package org.tio.sitexxx.service.service.stat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.tio.sitexxx.service.cache.CacheConfig;
import org.tio.sitexxx.service.cache.Caches;
import org.tio.sitexxx.service.model.main.ChatRecord;
import org.tio.sitexxx.service.model.main.IpInfo;
import org.tio.sitexxx.service.service.base.IpInfoService;
import org.tio.sitexxx.service.service.conf.ConfService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.utils.cache.CacheUtils;
import org.tio.utils.cache.FirsthandCreater;
import org.tio.utils.cache.ICache;
import org.tio.utils.hutool.StrUtil;
import org.tio.utils.lock.ListWithLock;
import org.tio.utils.lock.WriteLockHandler;

import com.jfinal.plugin.activerecord.Db;

/**
 * 聊天日志
 * @author tanyaowu
 *
 */
public class ChatRecordService {

	//	private static Logger log = LoggerFactory.getLogger(ChatRecordService.class);

	public static final ChatRecordService me = new ChatRecordService();

	static final ChatRecord dao = new ChatRecord().dao();

	static final ICache groupChatRecordCache = Caches.getCache(CacheConfig.GROUP_CHAT_LOG);

//	static final ICache P2P_CHATRECORD_CACHE = Caches.getCache(CacheConfig.P2P_CHAT_LOG);

	static final int DEFAULT_HISTORY_CHAT_COUNT_GROUP = 200;

//	static final int DEFAULT_HISTORY_CHAT_COUNT_P2P = 100;

	private ChatRecordService() {
	}

	//	public void addToQueue(ChatRecord chatRecord) {
	//		ChatRecordRunnable.me.addMsg(chatRecord);
	//		ChatRecordRunnable.me.execute();
	//		putToGroupCache(chatRecord);
	//	}
	//	
	public boolean save(ChatRecord chatRecord) {
		boolean f = chatRecord.save();
		if (f) {
//			if (StrUtil.isNotBlank(chatRecord.getGroupid())) {
				putToGroupCache(chatRecord);
//			} else {
//				putToP2pCache(chatRecord);
//			}
		}

		return f;
	}

	/**
	* 添加到群聊cache
	* @param chatRecord
	*/
	public void putToGroupCache(ChatRecord chatRecord) {
		String groupid = chatRecord.getGroupid();
		if (groupid != null) {
			ListWithLock<ChatRecord> listWithLock = ChatRecordService.me.getLastGroupChat(groupid);
			if (listWithLock != null) {
				listWithLock.handle(new WriteLockHandler<List<ChatRecord>>() {
					@Override
					public void handler(List<ChatRecord> list) {
						list.add(0, chatRecord);
						int historyCount = ConfService.getInt("im.history.chat.count.group", DEFAULT_HISTORY_CHAT_COUNT_GROUP);
						while (list.size() > historyCount) {
							list.remove(historyCount);
						}
					}
				});
			}
		}
	}

	/**
	 * 
	 * @param sessionid
	 * @param initContent
	 * @param displayContent
	 * @param fromUser
	 * @param fromIp
	 * @param groupid
	 * @param contenttype
	 * @return
	 */
	public ChatRecord saveChatRecord(String sessionid, String initContent, String displayContent, SimpleUser fromUser, String fromIp, String groupid,
	         Byte contenttype) {
		//存聊天日志
		IpInfo ipInfo = IpInfoService.ME.save(fromIp);
		//		RoomInst roomInst = ImServerService.me.getOnLive(groupid);
		ChatRecord chatRecord = new ChatRecord();
		chatRecord.setInput(initContent);
		chatRecord.setText(displayContent);
		chatRecord.setGroupid(groupid);
		chatRecord.setIpid(ipInfo.getId());
		//		if (roomInst != null) {
		//			chatRecord.setRoominstid(roomInst.getId());
		//		}
		chatRecord.setTime(new Date());
//		chatRecord.setTouid(touid);
		chatRecord.setUid(fromUser.getI());
		chatRecord.setSession(sessionid);
//		if (touid == null) {
//			chatRecord.setType(ChatRecord.Type.PUBLIC_CHAT);
//		} else {
//			chatRecord.setType(ChatRecord.Type.PRIVATE_CHAT);
//		}

		chatRecord.setContenttype(contenttype);
		//		chatRecord.setMid(mid);
		chatRecord.setStatus(ChatRecord.Status.OK);
		save(chatRecord);
		return chatRecord;
	}

	/**
	 * 
	 * @param mid
	 * @param status
	 * @author tanyaowu
	 */
	public void updateStatus(String mid, byte status) {
		String sql = "update chat_record set status = ? where id = ?";
		Db.use(Const.Db.TIO_SITE_MAIN).update(sql, status, Integer.parseInt(mid));

	}

	/**
	 * 
	 * @param groupid
	 */
	public void clearLastGroupChat(String groupid) {
		groupChatRecordCache.remove(groupid);
	}

	/**
	 * 
	 * @param mid 消息id
	 * @return
	 */
	public ChatRecord getByMid(String mid) {
		String sql = "select * from chat_record where id = ?";
		return dao.findFirst(sql, Integer.parseInt(mid));
	}

	/**
	 * 获取最近的群聊天记录
	 * @param uid
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ListWithLock<ChatRecord> getLastGroupChat(String groupid) {
		if (StrUtil.isBlank(groupid)) {
			return null;
		}
		String key = groupid;
		ListWithLock<ChatRecord> listWithLock = CacheUtils.get(groupChatRecordCache, key, false, new FirsthandCreater<ListWithLock<ChatRecord>>() {
			@Override
			public ListWithLock<ChatRecord> create() {
				int historyCount = ConfService.getInt("im.history.chat.count.group", DEFAULT_HISTORY_CHAT_COUNT_GROUP);
				ArrayList<ChatRecord> list = (ArrayList<ChatRecord>) dao.find("select * from chat_record where groupid = ? and status = 1 order by id desc limit ?", groupid,
				        historyCount);
				return new ListWithLock(list);
			}
		});
		return listWithLock;

	}




}
